<?php

function __autoload($class_name) {
    $fullclasspath = "";
    $suffix = "";
    if (!file_exists('inc/' . $fullclasspath . $class_name . ".php")) {
        if (!file_exists('inc/' . $fullclasspath . $class_name . ".class.php")) {
            if (file_exists('inc/utility/' . $class_name . ".class.php")) {
                $fullclasspath = "utility/";
                $suffix = ".class";
            }
        } else {
            $suffix = ".class";
        }
    }
    //echo 'inc/' . $fullclasspath . $class_name . $suffix . '.php<br />';
    require_once 'inc/' . $fullclasspath . $class_name . $suffix . '.php';
}

$text = '<html><body>prueba<p>Test paragraph.<a href="#fragment">Other text1</a></p></body></html>';
echo "\n";
$doc = new DOMDocument();
$doc->loadHTMLFile('http://localhost/alania21/newhtml-1.html');
$books = $doc->getElementsByTagName('html')->item(0);
$x = htmltoarray($books);
//$db = new connection();
//$content = AlaniaContenidosModel::findById($db->db, 1);
//$content->setPlantilla(json_encode($x));
//$content->updateToDatabase($db->db);

echo json_encode($x);

function htmltoarray($node) {

    $nodes[$node->nodeName] = [];


    $nodes[$node->nodeName]['hijos'] = [];
    if ($node->hasChildNodes()) {
        /* foreach ($node->childNodes as $n) {
          $nodes[$node->nodeName][$n->nodeName] = [];
          } */
        foreach ($node->childNodes as $n) {
            $x = htmltoarray($n);

            array_push($nodes[$node->nodeName]['hijos'], $x);
            //print_r($nodes);
        }
    } else {

        // $att=null;
        //if (isset($nodes[$node->nodeName]['attribites'])){
        //$att=$nodes[$node->nodeName]['attributes'];
        //}
        $nodes[$node->nodeName][0] = trim($node->nodeValue);
        //$nodes[$node->nodeName]['attributes']=$att;
    }
    $nodes[$node->nodeName]['attributes'] = getattributes($node);
    return $nodes;
}

function getattributes($node) {

    if ($node->attributes) {
        $length = $node->attributes->length;

        if ($length) {
            $attributes = [];
            for ($i = 0; $i < $length; ++$i) {
                $name = $node->attributes->item($i)->name;

                $attributes[$name] = $node->attributes->item($i)->value;
            }

            return $attributes;
        }
    }
    return "";
}